{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <style>
        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            font-size: 0.8rem;
            overflow: hidden;
        }

        .parent-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh; /* 或者设置一个固定的高度 */
        }

        .container {
            margin: 30px;
            width: 600px;
            padding: 50px 30px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

            display: flex;
            align-items: center;
            justify-content: center;
        }

        label {
            width: 400px;
            margin-bottom: 15px;
            display: flex block;
            align-items: center;
            justify-content: center;
        }

        input {
            padding: 15px;
            border: none;
            border-bottom: 1px #ccc solid;
            margin-bottom: 10px;
        }

        .input-group {
            width: 100%;
        }

        input[type="submit"], input[type="reset"] {
            background-color: rgba(76, 175, 80, 0.8);
            color: #fff;
            border: none;
            border-radius: 4px;
            padding: 10px 20px;
            cursor: pointer;
            margin: 10px 10px -10px;
        }
    </style>
    <script src="{% static 'js/alert.js' %}"></script>
    <script src="{% static 'js/validForm.js' %}"></script>
    <script src="{% static 'js/jquery-3.7.1.js' %}"></script>
    <script src="{% static 'js/ApiExceptionCodeEnums.js' %}"></script>
</head>
<body>
<div class="parent-container">
    <div class="container">

        <!--
        String pid, String appKey, String appSecret, String productKey, String deviceName, String identifier, String input

        itemValue.put("downUrl", "http://pre-apis-cn-hangzhou.qamsong.com:9001/cloud-boss//QS/dev/product/101/140/upgradefw/IPC-B22-IP_V0.0.13_240511_164055");
        itemValue.put("currentVersion", "IPC-B22-IP_V0.0.13_240511_164055");
        itemValue.put("targetVersion", "IPC-B22-IP_V0.0.13_240511_164055");
        itemValue.put("installPackMd5", "a86acb3d5b73256a62001a2bf95b43c0");
        itemValue.put("upRecordId", "1793182098350174211");
        itemValue.put("installPackSize", 37168256);

        -->
        <form method="POST" action="#" name="my_form" id="my_form">
            {% csrf_token %}
            <label>
                <input type="text" class="input-group" id="username" name="username" max="20"
                       placeholder="用户名">
            </label>
            <label>
                <input type="text" class="input-group" id="deviceName" name="deviceName" max="64"
                       placeholder="设备DN">
            </label>
            <label>
                <input type="text" class="input-group" id="downUrl" name="downUrl" max="1000"
                       placeholder="固件下载地址">
            </label>
            <label>
                <input type="text" class="input-group" id="md5" name="md5" readonly
                       placeholder="固件MD5">
            </label>
            <label>
                <input type="text" class="input-group" id="size" name="size" readonly
                       placeholder="固件大小">
            </label>
            <label>
                <input type="text" class="input-group" id="currentVersion" name="currentVersion" max="64"
                       placeholder="设备当前版本">
            </label>
            <label>
                <input type="text" class="input-group" id="targetVersion" name="targetVersion" max="64"
                       placeholder="升级目标版本">
            </label>

            <label>
                <input type="reset" value="重 置" class="input-group" id="resetButton">
                <input type="submit" value="提 交" class="input-group" id="submitButton"><span id="loadingIndicator"
                                                                                               style="display: none;">加载中</span>
            </label>
        </form>
    </div>
</div>

</body>

<script>
    let onfource = ["username", "deviceName", "downUrl", "currentVersion", "targetVersion"]
    let validNotEmptyList = ["username", "deviceName", "downUrl", "currentVersion", "targetVersion", "md5", "size"]

    for (let i = 0; i < onfource.length; i++) {
        onFocusInputNotEmpty(onfource[i]);
    }

    function validFormSubmit() {
        return onSubmitInputNotEmpty(validNotEmptyList)
    }

    // 重置逻辑
    document.getElementById('resetButton').addEventListener('click', function () {
        clearInputNotEmptyShow(validNotEmptyList);
    });
</script>

<script>
    // 获取表单元素
    const form = document.getElementById('my_form');

    // 表单提交事件处理函数
    function handleSubmit(event) {
        // 阻止表单的默认提交行为
        event.preventDefault();
        if (validateForm()) {
            // 在校验通过后禁用提交按钮
            disableSubmitButton();
            submitForm(event)
        }
    }

    // 表单校验函数
    function validateForm() {
        // 执行表单校验逻辑，返回校验结果
        // 如果校验通过，返回 true；否则返回 false
        return validFormSubmit()
    }

    // 绑定提交按钮的点击事件
    submitButton.addEventListener('click', handleSubmit);

    // 禁用提交按钮
    function disableSubmitButton() {
        console.log('禁用提交按钮');
        showLoading()
        $('#submitButton').prop('disabled', true);  // 禁用提交按钮
    }

    // 启用提交按钮
    function enableSubmitButton() {
        console.log('启用提交按钮');
        hideLoading()
        $('#submitButton').prop('disabled', false);  // 启用提交按钮
        return void 0;
    }

    let intervalId;  // 用于存储setInterval返回的ID

    // 在window加载后执行
    function showLoading() {
        // 模拟一个动态的三个点
        let dots = 0;
        const loadingText = "加载中";
        intervalId = setInterval(function () {
            dots++;
            if (dots > 3) {
                dots = 0;
            }
            const space = ' '.repeat(3 - dots)
            // 更新loadingIndicator文字
            const dynamicDots = ".".repeat(dots);
            document.getElementById('submitButton').value = loadingText + dynamicDots + space;
        }, 300);  // 每500毫秒更新一次动态的三个点
    }

    function hideLoading() {
        // 隐藏loadingIndicator
        clearInterval(intervalId);  // 停止动态的三个点
        document.getElementById('submitButton').value = "提 交";
    }
</script>
<script>
    // 表单提交事件处理函数
    function submitForm(event) {
        // 发送AJAX请求到 api 进行校验
        fetch('{% url 'apiUpgrade' %}', {
            method: 'POST',
            body: new FormData(form)
        })
            .then(response => response.json())
            .then(data => {
                // 校验成功后提交表单到action页面
                showApiRespMessage(data.code)
                console.log("接口返回数据：", data)
                setTimeout(function () {
                    // 在定时器执行完毕后启用提交按钮
                    enableSubmitButton();
                }, 2000);
            })
            .catch(error => {
                // 处理请求错误
                alert_error("网络异常，请联系管理员 !!!")
                console.error('Error:', error);
            }).finally(
            // 无论是否成功，都要启用提交按钮
            enableSubmitButton()
        );
    }

    function showApiRespMessage(code) {
        // 根据code显示对应的错误信息
        const msg = ApiExceptionCodeEnums[code]
        if (msg) {
            alert_error(msg)
        } else {
            alert_error("未知错误，请联系管理员 !!!")
        }

    }

    function formDataToJson(formData) {
        const jsonObject = {};
        for (const [key, value] of formData.entries()) {
            jsonObject[key] = value;
        }
        return jsonObject;
    }

    function getInputValueById(id) {
        return document.getElementById(id).value;
    }

</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/spark-md5/3.0.0/spark-md5.min.js"></script>
<script>
    // 计算文件MD5和大小的函数
    function calculateMD5AndSize(url, callback) {
        const xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = function (event) {
            const blob = xhr.response;
            const fileReader = new FileReader();
            fileReader.onload = function (e) {
                const spark = new SparkMD5.ArrayBuffer();
                spark.append(e.target.result);
                const md5Value = spark.end(false);
                const fileSize = blob.size;
                callback({md5: md5Value, size: fileSize});
            };
            fileReader.readAsArrayBuffer(blob);
        };
        xhr.open('GET', url);
        xhr.send();
    }

    // 监听downUrl输入框变化
    $('#downUrl').on('input', function () {
        const url = $(this).val();
        if (url) {
            calculateMD5AndSize(url, function (data) {
                $('#md5').val(data.md5);  // 更新md5输入框的值
                $('#size').val(data.size);  // 更新size输入框的值
            });
        } else {
            $('#md5').val('');  // 清空md5输入框
            $('#size').val('');  // 清空size输入框
        }
    });
</script>
</html>
